// https://www.lintcode.com/problem/insert-interval/description
// 30. 插入区间
// Given a non-overlapping interval list which is sorted by start point.

// Insert a new interval into it, make sure the list is still in order and non-overlapping (merge intervals if necessary).

// 样例
// Insert (2, 5) into [(1,2), (5,9)], we get [(1,9)].

// Insert (3, 4) into [(1,2), (5,9)], we get [(1,2), (3,4), (5,9)].



/**
 * Definition of Interval:
 * classs Interval {
 *     int start, end;
 *     Interval(int start, int end) {
 *         this->start = start;
 *         this->end = end;
 *     }
 * }
 */

// 不断更新newInterval的值作为下一轮要和intervals中的区间合并的新区间
class Solution {
public:
    /**
     * @param intervals: Sorted interval list.
     * @param newInterval: new interval.
     * @return: A new interval list.
     */
    vector<Interval> insert(vector<Interval> &intervals, Interval newInterval) {
        vector<Interval> result;
        int insert_pos = 0;
        for (Interval i: intervals)
        {
            if (i.end < newInterval.start)
            {
                insert_pos++;
                result.push_back(i);
            }
            else if (i.start > newInterval.end)
            {
                result.push_back(i);
            }
            else
            {
                newInterval.start = min(i.start, newInterval.start);
                newInterval.end = max(i.end, newInterval.end);
            }
        }
        result.insert(result.begin() + insert_pos, newInterval);
        return result;
    }
};